<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\TaskDetailResource;
use App\Models\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Jiannei\Response\Laravel\Support\Facades\Response;
use App\Http\Resources\TaskCollection;

class TaskController extends Controller
{
    public function index()
    {
        $tasks = Task::where('status', 0)->get();
        return Response::success(new TaskCollection($tasks), '操作成功');
    }

    public function show($id)
    {
        $task = Task::query()->leftJoin('task_detail', 'task_detail.task_id', '=', 'task.id')->where('task.id', $id)->select(['task.*', 'task_detail.detail','task_detail.certified_chart'])->firstOrFail();
        return Response::success(new TaskDetailResource($task), '操作成功');
    }

    public function store(Request $request){
        $category = $request->category;
        $type = $request->type;
        $singular = $request->singular;
        $price = $request->price;
        $valid_time = $request->valid_time;
        $detail = $request->detail;
        $certified_chart = $request->certified_chart;
        if ($singular && $price && $valid_time && $certified_chart && $detail){
            return Response::fail('必填字段未填写');
        }

        DB::beginTransaction();
        try {
            $insetId = DB::table('task')->insertGetId(array(
                'category' => $category,
                'type' => $type,
                'singular' => $singular,
                'price' => $price,
                'valid_time' => $valid_time,
            ));
            DB::table('task_detail')->insert(array(
                'task_id' => $insetId,
                'detail' => $detail,
                'certified_chart' => $certified_chart,
            ));
            DB::commit();
            return Response::created();
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

}
